<script setup>
import { reactive, ref, watch } from 'vue'
import { queryUserList } from '@/service/user.js'
import { displayLoading } from '@/utils/loading.js'
import dayjs from 'dayjs'
const shortcuts = [
  {
    text: '今天',
    value: () => {
      const date = new Date()
      // 今天：开始和结束都是当前日期（精确到日）
      return [new Date(date.setHours(0, 0, 0, 0)), new Date(date.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '昨天',
    value: () => {
      const end = new Date()
      const start = new Date()
      // 昨天：开始=昨天0点，结束=昨天23:59:59
      start.setDate(start.getDate() - 1)
      end.setDate(end.getDate() - 1)
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '本月',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), end.getMonth(), 1) // 本月1号
      // 本月：开始=本月1号0点，结束=当前日期23:59:59（未到月底时）
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '上月',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), end.getMonth() - 1, 1) // 上月1号
      const lastDayOfLastMonth = new Date(end.getFullYear(), end.getMonth(), 0) // 上月最后一天
      // 上月：开始=上月1号0点，结束=上月最后一天23:59:59
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(lastDayOfLastMonth.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '最近七天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 6) // 今天往前推6天（含今天共7天）
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '最近三十天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 29) // 今天往前推29天（含今天共30天）
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '最近九十天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 89) // 今天往前推89天（含今天共90天）
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '最近一年',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setFullYear(start.getFullYear() - 1) // 今天往前推1年
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '今年',
    value: () => {
      const end = new Date()
      const start = new Date(end.getFullYear(), 0, 1) // 今年1月1号
      // 今年：开始=1月1号0点，结束=当前日期23:59:59
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
  {
    text: '去年',
    value: () => {
      const year = new Date().getFullYear() - 1
      const start = new Date(year, 0, 1) // 去年1月1号
      const end = new Date(year, 11, 31) // 去年12月31号
      // 去年：完整一整年
      return [new Date(start.setHours(0, 0, 0, 0)), new Date(end.setHours(23, 59, 59, 999))]
    },
  },
]
const searchForm = reactive({
  searchCondition: 0,
  searchField: '',
  registrationDate: null,
  minimumConsumptionAmount: null,
  maximumConsumptionAmount: null,
})

const userList = ref([])
const totalCount = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

watch(
  [currentPage, pageSize],
  () => {
    loadData()
  },
  { immediate: true }
)

async function loadData() {
  let userName = null,
    userId = null,
    phoneNumber = null,
    registrationStartDate = null,
    registrationEndDate = null,
    minimumConsumptionAmount = searchForm.minimumConsumptionAmount,
    maximumConsumptionAmount = searchForm.maximumConsumptionAmount,
    _page = currentPage.value,
    _pageSize = pageSize.value
  if (searchForm.searchCondition === 0) {
    userName = searchForm.searchField
  } else if (searchForm.searchCondition === 1) {
    userId = searchForm.searchField
  } else if (searchForm.searchCondition === 2) {
    phoneNumber = searchForm.searchField
  }
  if (searchForm.registrationDate) {
    registrationStartDate = dayjs(searchForm.registrationDate[0]).format('YYYY-MM-DD')
    registrationEndDate = dayjs(searchForm.registrationDate[1]).format('YYYY-MM-DD')
  }
  const res = await displayLoading(() =>
    queryUserList(
      userName,
      userId,
      phoneNumber,
      registrationStartDate,
      registrationEndDate,
      minimumConsumptionAmount,
      maximumConsumptionAmount,
      _page,
      _pageSize
    )
  )
  console.log(res)
  totalCount.value = res.data.total
  userList.value = res.data.records
}

function onTapQueryButton() {
  loadData()
}

function onTapClearQueryButton() {
  Object.assign(searchForm, {
    searchCondition: 0,
    searchField: '',
    registrationDate: null,
    minimumConsumptionAmount: null,
    maximumConsumptionAmount: null,
  })
  pageSize.value = 10
  currentPage.value = 1
  loadData()
}

function onTapCheckUserInfo(row){

}

function onTapEditUserInfo(row){

}
function onTapAdjustUserInfo(row){

}
</script>

<template>
  <div class="customer-page">
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="会员信息:">
        <el-select v-model="searchForm.searchCondition" class="select-keyword" style="width: 130px">
          <el-option :value="0" label="会员昵称" />
          <el-option :value="1" label="会员编号" />
          <el-option :value="2" label="会员手机号码" />
        </el-select>
        <el-input
          v-model="searchForm.searchField"
          class="input-keyword"
          placeholder="请输入关键词"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="消费金额:">
        <el-input-number v-model="searchForm.minimumConsumptionAmount" :controls="false" :precision="2">
          <template #prefix>
            <span>￥</span>
          </template>
        </el-input-number>
        <span style="margin: 0 10px"> ~ </span>
        <el-input-number v-model="searchForm.maximumConsumptionAmount" :controls="false" :precision="2">
          <template #prefix>
            <span>￥</span>
          </template>
        </el-input-number>
      </el-form-item>
      <br />
      <el-form-item label="注册时间:">
        <el-date-picker
          v-model="searchForm.registrationDate"
          :shortcuts="shortcuts"
          end-placeholder="结束时间"
          range-separator="~"
          start-placeholder="开始时间"
          style="width: 350px"
          type="daterange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onTapQueryButton">查询</el-button>
        <el-button type="default" @click="onTapClearQueryButton">清空查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="userList"
      :header-cell-style="() => ({ background: '#eef1f6', color: '#606266' })"
      border
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="用户ID">
        <template #default="scope">
          <span>{{ scope.row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="头像">
        <template #default="scope">
          <el-image :src="scope.row.userAvatar" style="width: 60px; height: 60px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="昵称" width="100">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" width="100">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.phoneNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="余额">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.balance.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="消费金额">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.balance.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="注册时间" width="140">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.registrationDate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后登录时间" width="140">
        <template #default="scope">
          <span style="font-size: 12px">{{ scope.row.lastLoginDate }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" fixed="right" width="260">
        <template #default="scope">
          <el-button type="default" @click="onTapCheckUserInfo(scope.row)">资料</el-button>
          <el-button type="primary" @click="onTapEditUserInfo(scope.row)">编辑</el-button>
          <el-button type="warning" @click ="onTapAdjustUserInfo(scope.row)">账户调整</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px"
    />
  </div>
</template>

<style lang="scss" scoped>
.customer-page {
  background: #fff;
  padding: 24px;
}
/* 移除 el-select 右侧圆角（正确层级） */
:deep(.select-keyword .el-select__wrapper) {
  border-radius: 4px 0 0 4px !important; /* 只保留左侧圆角 */
  background-color: #fafafa;
}

/* 移除 el-input 左侧圆角（正确层级） */
:deep(.input-keyword .el-input__wrapper) {
  border-radius: 0 4px 4px 0 !important; /* 只保留右侧圆角 */
  margin-left: -1px; /* 抵消边框重叠 */
  border-left: none; /* 彻底移除左侧边框，避免重叠残留 */
}

/* 聚焦状态优化 */
:deep(.select-keyword .el-select__wrapper:focus-within) {
  z-index: 1; /* 确保聚焦边框不被 input 覆盖 */
}
</style>
